<?php
namespace froyo\cherry\Base;
use froyo\cherry\Exception\InvalidCallException;
use froyo\cherry\Exception\UnknownPropertyException;


class LangFactory extends BaseObject{
	public $lang = 'zh-cn';
	public $langMaps = [];
	public $applang = 'app';

	public function loadmodulelang($module,$path){
		if(file_exists($path))
		{
			$this->langMaps[ $module ] = require $path;
		}
	}

	public function init_(){
		$path = CHERRY_APP_ROOT.'/lang/'.$this->applang.'/'.$this->lang.'.php';
		$this->loadmodulelang($this->applang,$path);
	}

	protected function getlang($module,$str)
	{
		if(isset($this->langMaps[ $module ]) && isset($this->langMaps[ $module ][ $str ]))
		{
			return $this->langMaps[ $module ][ $str ];
		}
		return $str;
	}

	public function lang($str,$params=[],$module='')
	{
		if($module == '')
		{
			$module = $this->applang;
		}
		$str = $this->getlang($module,$str);
		$replacesfrom = [];
		$replacesto = [];
		foreach ($params as $key => $value) {
			if(strpos($key, ':') === 0)
			{
				$replacesfrom[] = '{'.$key.'}';
				$replacesto[] = $value;				
			}
		}

		if($replacesfrom)
		{
			$str = str_replace($replacesfrom, $replacesto, $str);
		}
		return $str;
	}
}